package com.psct.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.actionbarsherlock.widget.ShareActionProvider.OnShareTargetSelectedListener;
import com.psct.PSCTUtil;
import com.psct.R;
import com.psct.bean.Criticism;
import com.psct.bean.ImageRes;
import com.psct.data.PSCTDatabase;
import com.psct.fragment.CriticismFragment;
import com.psct.fragment.ImageShowFragment;
import com.psct.web.HttpUtil;

public class TextShowActivity extends SherlockFragmentActivity implements OnClickListener,OnShareTargetSelectedListener {
	protected static final String TAG = "imageShow";
	private TextView title;
	private Button othersBtn;
	private Button mySelfBtn;
	/**
	 * 评论碎片
	 */
	CriticismFragment cFragment;
	/**
	 * 课文图片碎片
	 */
	ImageShowFragment isFragment;
	/**
	 * 分享
	 */
	ShareActionProvider actionProvider;
	private boolean isImage = true;
	private boolean isFirstShowCriticism = true;
	// 传入参数
	ArrayList<String> imagePathList;
	private int textId;
	private String textTitle;
	private Handler handler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				imagePathList = (ArrayList<String>) msg.obj;
				FragmentManager fm = getSupportFragmentManager();
				if (isFragment == null)
					isFragment = ImageShowFragment.newInstance(imagePathList);
				FragmentTransaction transation = fm.beginTransaction();
				transation.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				transation.add(R.id.fragment, isFragment);
				transation.commit();
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActionBar actionBar = this.getSupportActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.actionbar_bg));
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setTitle(textTitle);
		setContentView(R.layout.activity_textshow);
		textId = getIntent().getIntExtra("textId", -1);
		textTitle = getIntent().getStringExtra("textTitle");
		title = (TextView) findViewById(R.id.tv_title);
		othersBtn = (Button) findViewById(R.id.btn_others);
		othersBtn.setOnClickListener(this);
		mySelfBtn = (Button) findViewById(R.id.btn_self);
		mySelfBtn.setOnClickListener(this);
		// 开线程通过课文id去数据库查找图片集
		getImagePathById(textId);
	}

	/**
	 * 查询数据库，获得图片的url
	 * 
	 * @param id
	 */
	private void getImagePathById(final int id) {
		new Thread() {
			public void run() {
				PSCTDatabase db = new PSCTDatabase(TextShowActivity.this);
				// 去数据库查询图片地址：
				List<String> imagePath = db.querryImagePathByTextID(id);
				Log.v(TAG, "数据库查询结果："+imagePath.size());
				// 数据库没有则去服务器查询
				if (imagePath.isEmpty()) {
					ImageRes res = new HttpUtil(TextShowActivity.this)
							.getImageUrlListByTextId(textId);
					if (res.res == 0) {
						Log.v(TAG, "服务器查询结果："+imagePath.size());
						imagePath.addAll(res.urlList);
						//添加到数据库
						db.addImagePath(id,res.urlList);
					}
				}

				Message m = handler.obtainMessage(0);
				m.obj = imagePath;
				handler.sendMessage(m);
			}
		}.start();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.share_action_provider, menu);
		MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);
		actionProvider = (ShareActionProvider) actionItem.getActionProvider();
		actionProvider.setShareHistoryFileName(ShareActionProvider.DEFAULT_SHARE_HISTORY_FILE_NAME);
		actionProvider.setShareIntent(createShareIntent());
		actionProvider.setOnShareTargetSelectedListener(this);
		return true;
	}

	/**
	 * 创建分享intent
	 * 
	 * @return
	 */
	private Intent createShareIntent() {
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.setType("image/*");
		Uri uri = Uri.fromFile(getFileStreamPath("shared.jpg"));
		// TODO 分享内容
		shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
		return shareIntent;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_others:
			switchBtnStatu((Button) v);
			break;
		case R.id.btn_self:
			Intent intent = new Intent(this, AddCriticismActivity.class);
			intent.putExtra("textId", textId);
			intent.putStringArrayListExtra("imagePathList", imagePathList);
			this.startActivityForResult(intent, 0);
			break;
		}
	}

	/**
	 * 切换状态
	 */
	protected void switchBtnStatu(Button v) {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transation = fm.beginTransaction();
		if (isImage) {
			if (isFirstShowCriticism) {
				if (cFragment == null)
					cFragment = CriticismFragment.newInstance(textId);
				transation.add(R.id.fragment, cFragment);
				isFirstShowCriticism = false;
			} else {
				transation.show(cFragment);
			}
			transation.hide(isFragment);
			v.setText("查看课文");
			isImage = false;
		} else {
			transation.show(isFragment);
			transation.hide(cFragment);
			v.setText("别人的记忆");
			isImage = true;
		}
		transation.commit();
	}

	/**
	 * 分享按钮回调方法
	 * @param source
	 * @param intent
	 * @return
	 */
	@Override
	public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
		Log.v("share", intent.getType());
		PSCTUtil.saveShareImage(this,imagePathList);
		intent.setType("image/*");
		Uri uri = Uri.fromFile(getFileStreamPath("shared.jpg"));
		Log.v("share", "分享路径："+getFileStreamPath("shared.jpg").getAbsolutePath());
		// TODO 分享内容
		intent.putExtra(Intent.EXTRA_STREAM, uri);
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode==0&&data!=null) {
			if(resultCode==0) {
				Criticism c = (Criticism) data.getSerializableExtra("criticism");
				if(c!=null&&cFragment!=null) {
					cFragment.upLoad(c);
				}
			}
			
		}
		super.onActivityResult(requestCode, resultCode, data);
		
	}
	
	
}
